package com.lk.user.service.impl;

import com.lk.basic.util.SmsUtil;
import com.lk.basic.util.VerifyCodeUtils;
import com.lk.user.domain.Logininfo;
import com.lk.user.dto.ChangePasswordCodeDTO;
import com.lk.user.dto.RegisterSmsCodeDTO;
import com.lk.user.dto.VerificationCodeDTO;
import com.lk.user.mapper.LogininfoMapper;
import com.lk.user.service.IVerifyCodeService;
import com.sun.xml.internal.ws.api.pipe.ServerPipeAssemblerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public String getImageCode(String key) throws Exception {
        //生成4位随机验证码
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        System.out.println(verifyCode);
        //将验证码存入redis：key
        redisTemplate.opsForValue().set(key,verifyCode,3, TimeUnit.MINUTES);
        //将验证码合并到图片中，获取Base64加密字符串
        String base64Code = VerifyCodeUtils.VerifyCode(100, 40, verifyCode);
        //将加密字符串返回
        return base64Code;
    }

    @Override
    public void sendRegisterSmsCode(RegisterSmsCodeDTO dto) {
        String mobile = dto.getMobile();
        String imageCode = dto.getImageCode();
        String imageCodeKey = dto.getImageCodeKey();
        //registerImageCodeKey
        //参数校验
        //非空校验
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(imageCode) || StringUtils.isEmpty(imageCodeKey)){
            throw new RuntimeException("参数异常");
        }
        //图形验证码是否正确
        String imageCodeRedis = (String) redisTemplate.opsForValue().get(imageCodeKey);
        if (StringUtils.isEmpty(imageCodeRedis) || !imageCodeRedis.equals(imageCode)){
            throw new RuntimeException("图形验证码错误");
        }
        //判断是否注册
        Logininfo logininfo=logininfoMapper.findUserByMobile(mobile);
        if (Objects.nonNull(logininfo)){
            throw  new RuntimeException("该手机号已被注册");
        }
        //获取当前手机号知否存在验证码
        String smsCodeStr=(String) redisTemplate.opsForValue().get("rediser_sms_code_"+mobile);
        String smsCode="";
        if (StringUtils.isEmpty(smsCodeStr)){
            //不存在 重新生成一个新的验证码
            smsCode=VerifyCodeUtils.generateVerifyCode(4);
            System.out.println(smsCode);
        }else {
            //已存在，是否已过重发时间 未过，提示报错信息，已过重发验证码
            smsCode = smsCodeStr.split(":")[0];
            long sendTime=Long.parseLong(smsCodeStr.split(":")[1]);
            if (System.currentTimeMillis()-sendTime<60*1000){
                throw new RuntimeException("请勿频繁操作");
            }
        }
        // 存入redis并设置过期时间
        redisTemplate.opsForValue().set("rediser_sms_code_"+mobile,smsCode+":"+System.currentTimeMillis(),5,TimeUnit.MINUTES);

        //发送短信
        String smsText="验证码是%s,有效期%s";
        //SmsUtil.sendSms(mobile,String.format(smsText,smsCode,5));
        System.out.println(String.format(smsText,smsCode,5));




    }

    @Override
    public void verificationCode(VerificationCodeDTO dto) {
        String username = dto.getUsername();
        String verify = dto.getVerify();
        if (StringUtils.isEmpty(username)){
            throw new RuntimeException("参数有错误");
        }
        Logininfo logininfo=logininfoMapper.findUserByPhone(username);
        if (!Objects.nonNull(logininfo)){
            throw  new RuntimeException("该手机号还未注册");
        }
        String smsCodeStr=(String) redisTemplate.opsForValue().get("login_sms_code_"+username);
        String smsCode="";
        if (StringUtils.isEmpty(smsCodeStr)){
            //不存在 重新生成一个新的验证码
            smsCode=VerifyCodeUtils.generateVerifyCode(4);
            System.out.println(smsCode);
        }else {
            //已存在，是否已过重发时间 未过，提示报错信息，已过重发验证码
            smsCode = smsCodeStr.split(":")[0];
            long sendTime=Long.parseLong(smsCodeStr.split(":")[1]);
            if (System.currentTimeMillis()-sendTime<60*1000){
                throw new RuntimeException("请勿频繁操作");
            }
        }
        // 存入redis并设置过期时间
        redisTemplate.opsForValue().set("login_sms_code_"+username,smsCode+":"+System.currentTimeMillis(),5,TimeUnit.MINUTES);

        //发送短信
        String smsText="验证码是%s,有效期%s";
        //SmsUtil.sendSms(mobile,String.format(smsText,smsCode,5));
        System.out.println(String.format(smsText,smsCode,5));

    }

    @Override
    public void changePassword(ChangePasswordCodeDTO dto) {
        String username = dto.getUsername();//用户名
        String password = dto.getPassword();//密码
        String confirmpassword = dto.getConfirmpassword();//确认密码
        String verify = dto.getVerify();//验证码
        if (StringUtils.isEmpty(username)){
            throw new RuntimeException("参数有错误");
        }
        Logininfo logininfo=logininfoMapper.findUserByPhone(username);
        if (!Objects.nonNull(logininfo)){
            throw  new RuntimeException("该手机号还未注册");
        }
        String smsCodeStr=(String) redisTemplate.opsForValue().get("login_sms_code_"+username);
        String smsCode="";
        if (StringUtils.isEmpty(smsCodeStr)){
            //不存在 重新生成一个新的验证码
            smsCode=VerifyCodeUtils.generateVerifyCode(4);
            System.out.println(smsCode);
        }else {
            //已存在，是否已过重发时间 未过，提示报错信息，已过重发验证码
            smsCode = smsCodeStr.split(":")[0];
            long sendTime=Long.parseLong(smsCodeStr.split(":")[1]);
            if (System.currentTimeMillis()-sendTime<60*1000){
                throw new RuntimeException("请勿频繁操作");
            }
        }
        // 存入redis并设置过期时间
        redisTemplate.opsForValue().set("login_sms_code_"+username,smsCode+":"+System.currentTimeMillis(),5,TimeUnit.MINUTES);

        //发送短信
        String smsText="验证码是%s,有效期%s";
        //SmsUtil.sendSms(mobile,String.format(smsText,smsCode,5));
        System.out.println(String.format(smsText,smsCode,5));
    }

    @Override
    public void sendBinderSmsCode(RegisterSmsCodeDTO dto) {
        String mobile = dto.getMobile();
        //registerImageCodeKey
        //参数校验
        //非空校验
        if (StringUtils.isEmpty(mobile)){
            throw new RuntimeException("参数异常");
        }
        //获取当前手机号知否存在验证码
        String smsCodeStr=(String) redisTemplate.opsForValue().get("binder_sms_code_"+mobile);
        String smsCode="";
        if (StringUtils.isEmpty(smsCodeStr)){
            //不存在 重新生成一个新的验证码
            smsCode=VerifyCodeUtils.generateVerifyCode(4);
            System.out.println(smsCode);
        }else {
            //已存在，是否已过重发时间 未过，提示报错信息，已过重发验证码
            smsCode = smsCodeStr.split(":")[0];
            long sendTime=Long.parseLong(smsCodeStr.split(":")[1]);
            if (System.currentTimeMillis()-sendTime<60*1000){
                throw new RuntimeException("请勿频繁操作");
            }
        }
        // 存入redis并设置过期时间
        redisTemplate.opsForValue().set("binder_sms_code_"+mobile,smsCode+":"+System.currentTimeMillis(),5,TimeUnit.MINUTES);

        //发送短信
        String smsText="验证码是%s,有效期%s";
        //SmsUtil.sendSms(mobile,String.format(smsText,smsCode,5));
        System.out.println(String.format(smsText,smsCode,5));
    }
}
